<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header">
            <span>部门列表</span>
            <el-button
              type="text"
              style="float: right"
              icon="el-icon-plus"
              @click="handleViewFirst"
            >
              查看一级
            </el-button>
          </div>
          <el-tree
            ref="departmentTree"
            v-loading="treeLoading"
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="18">
        <el-collapse-transition>
          <el-card v-show="isFilterVisible" class="search-wrapper">
            <el-form :inline="true" :model="selDepartmentListQuery">
              <el-form-item label="部门名称">
                <el-input
                  v-model="selDepartmentListQuery.name"
                  clearable
                  placeholder="请输入部门名称"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-collapse-transition>
        <el-card>
          <div>
            <div class="table-operations">
              <el-button
                type="primary"
                size="small"
                class="filter-trigger"
                @click="isFilterVisible = !isFilterVisible"
              >{{ isFilterVisible ? "收起" : "检索" }}
                <i
                  :class="[
                    'el-icon-arrow-down',
                    { 'is-reverse': isFilterVisible },
                  ]"
                />
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="handleAdd"
              >新建</el-button>
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="handleBatchDelete"
              >批量删除</el-button>
              <!-- <el-dropdown style="float: right">
                <el-button size="small">
                  更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>导入</el-dropdown-item>
                  <el-dropdown-item>导出</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
            </div>

            <el-table
              :data="tableData"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form
                    label-position="left"
                    inline
                    class="demo-table-expand"
                  >
                    <el-form-item label="部门名称">
                      <span>{{ props.row.name }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ formatCreateTime(props.row.createTime) }}</span>
                    </el-form-item>
                    <el-form-item label="更新时间">
                      <span>{{ formatCreateTime(props.row.updateTime) }}</span>
                    </el-form-item>
                    <el-form-item label="部门ID">
                      <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item label="父级ID">
                      <span>{{ props.row.parentId }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column label="部门名称" prop="name" />
              <!-- <el-table-column label="创建时间" prop="createTime">
                <template slot-scope="scope">
                  <span>{{ formatCreateTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="parentMenu"
                label="父级菜单"
              ></el-table-column> -->
              <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页 -->
          <el-row
            :gutter="10"
            style="margin-top: 20px"
            type="flex"
            justify="end"
          >
            <el-pagination
              background
              :current-page="selDepartmentListQuery.page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="selDepartmentListQuery.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门名称:" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入部门名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selDepartmentListApi,
  addDepartmentApi,
  updateDepartmentByIdApi,
  delDepartmentByIdsApi,
  selDepartmentByIdApi
} from '@/api/system'
import { processMenuData } from '@/utils/menuHelper'

export default {
  name: 'Department',
  data() {
    return {
      treeData: [],
      treeLoading: false,
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 表格数据
      tableData: [],
      // 新增部门参数
      addDepartmentQuery: {
        name: '',
        parentId: 0
      },
      // 部门管理查询参数
      selDepartmentListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      dialogVisible: false,
      selDepartmentLists: [],
      // 总条数
      total: 0,
      // 选中的行
      selectedRows: [],
      isFilterVisible: false,
      dialogTitle: '',
      currentNode: null,
      formData: {
        name: '',
        parentId: null,
        id: null
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 获取部门列表数据
    async getDepartmentList() {
      // this.treeLoading = true;
      try {
        const res = await selDepartmentListApi(this.selDepartmentListQuery)
        console.log(res)
        this.treeData = this.formatTreeData(res.records)
        console.log(this.treeData)
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.$message.error('获取部门列表失败，请重试')
      } finally {
        // this.treeLoading = false;
      }
    },

    // 格式化树形数据
    formatTreeData(data) {
      if (!data) return []

      return data.map((item) => {
        const node = {
          id: item.id || null,
          name: item.name,
          parentId: item.parentId || null,
          createTime: item.createTime,
          updateTime: item.updateTime
        }

        // 如果有子节点，递归处理
        if (item.list && item.list.length > 0) {
          node.list = this.formatTreeData(item.list)
        } else {
          node.list = [] // 确保没有子节点时也有list属性
        }

        return node
      })
    },

    // 树节点点击事件
    async handleNodeClick(data) {
      this.currentNode = data
      const res = await selDepartmentByIdApi(data.id)
      console.log(res)

      // 处理返回的数据
      if (res.data.list && res.data.list.length > 0) {
        // 如果有子列表，显示子列表
        this.tableData = res.data.list
      } else {
        // 如果没有子列表或list为空数组，显示当前部门数据
        this.tableData = [
          {
            id: res.data.id,
            name: res.data.name,
            createTime: res.data.createTime,
            updateTime: res.data.updateTime,
            parentId: res.data.parentId
          }
        ]
      }
    },

    // 查看一级部门
    handleViewFirst() {
      // 实现查看一级部门的逻辑
      this.$refs.departmentTree.setCheckedKeys([])
    },
    async selDepartmentList() {
      const res = await selDepartmentListApi(this.selDepartmentListQuery)
      console.log(res)
      this.selDepartmentLists = res.records
      this.total = res.total
    },
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 查询
    handleQuery() {
      this.selDepartmentListQuery.page = 1
      this.selDepartmentList()
    },
    // 重置
    resetQuery() {
      this.selDepartmentListQuery = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selDepartmentList()
    },
    // 新增部门
    handleAdd() {
      this.dialogTitle = '新增部门'
      this.dialogVisible = true
      this.formData = {
        name: '',
        parentId: this.currentNode.id
      }
    },
    // 编辑部门
    handleEdit(row) {
      this.dialogTitle = '编辑部门'
      this.dialogVisible = true
      this.formData = {
        name: row.name,
        id: row.id,
        parentId: row.parentId
      }
    },
    // 删除部门
    handleDelete(row) {
      this.$confirm('确认删除该部门?', '提示', {
        type: 'warning'
      }).then(async() => {
        try {
          await delDepartmentByIdsApi([row.id])
          this.$message.success('删除成功')
          this.getDepartmentList()
          if (this.currentNode) {
            this.handleNodeClick(this.currentNode)
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        return this.$message.warning('请选择要删除的部门')
      }

      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 个部门?`, '提示', {
        type: 'warning'
      }).then(async() => {
        try {
          const ids = this.selectedRows.map(row => row.id)
          await delDepartmentByIdsApi(ids)
          this.$message.success('删除成功')
          this.getDepartmentList()
          if (this.currentNode) {
            this.handleNodeClick(this.currentNode)
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.selDepartmentListQuery.pageSize = val
      this.selDepartmentList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.selDepartmentListQuery.page = val
      this.selDepartmentList()
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            if (this.formData.id) {
              // 编辑
              await updateDepartmentByIdApi(this.formData)
              this.$message.success('编辑成功')
            } else {
              // 新增只传 name 和 parentId
              const addData = {
                name: this.formData.name,
                parentId: this.formData.parentId
              }
              await addDepartmentApi(addData)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            this.getDepartmentList()
            if (this.currentNode) {
              this.handleNodeClick(this.currentNode)
            }
          } catch (error) {
            this.$message.error(this.formData.id ? '编辑失败' : '新增失败')
          }
        }
      })
    },
    // 执行时间处理
    handleDurationChange(val) {
      if (!val || val.length !== 2) return

      // 提取日期部分（去掉时间）
      const startDate = val[0].split(' ')[0]
      const endDate = val[1].split(' ')[0]

      // 组合成最终格式
      this.formData.duration = `${startDate},${endDate}`

      console.log('执行时间:', this.formData.duration)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.search-wrapper {
  margin-bottom: 16px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button--text {
  padding: 0 8px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff;
  color: #409eff;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
